Skip to content

Let trigger expressions start and end with blanks and span lines (#617) - #921

Merged
craigbarratt merged 2 commits into
custom-components:masterfrom
HoneyBearTech:fix-trigger-expr-whitespace-617
Nov 22, 2026
Merged

craigbarratt merged 2 commits into
custom-components:masterfrom
HoneyBearTech:fix-trigger-expr-whitespace-617

Conversation

@HoneyBearTech

@HoneyBearTech HoneyBearTech commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Closes #617

What was broken
A trigger expression that starts with a space or tab (also after a new line) fails, and the trigger is never created:

@state_trigger(""" pyscript.a == 'x'""")      # IndentationError: unexpected indent
def f(): ...

task.wait_until(state_trigger=" pyscript.a == 'x'")   # IndentationError

An expression written over several lines without brackets around the whole of it fails too. #617's own example is like this: its lines end in and.

_state_sensor = 'sensor.office_state'
@state_trigger(f"""
{_state_sensor} in ['recently occupied', 'unoccupied', 'dormant', 'unavailable'] and
(sensor.octoprint_actual_tool0_temp == 'unavailable' or float(sensor.octoprint_actual_tool0_temp) <= 110) and
(sensor.octoprint_actual_bed_temp == 'unavailable' or float(sensor.octoprint_actual_bed_temp) <= 110)
""", state_hold_false=0)                      # SyntaxError: invalid syntax, with or without the blanks
def should_turn_off(): ...

It was also inconsistent. The same multi-line text worked as one of several @state_trigger entries, because those are joined into one any([...]) and so sit inside brackets. On its own it failed.

A bare state name with blanks around it was also wrong. " pyscript.a" didn't match the "any change" pattern, so it became the expression pyscript.a (true or false by value). "pyscript.a\n" did match, but the name kept its new line, so it never matched the real entity.

Why

  • Trigger expressions are parsed in mode="eval", exactly as written. Python's rules for a bare expression apply there: no spaces or tabs before it, and a line break only inside brackets or after a \.
  • With several @state_trigger entries, the entries are joined into any([...]), so they are inside brackets and those rules don't bite. A single entry isn't inside any brackets, so the same text fails there.
  • Bare names were recognised with a regular expression on the raw string, before any cleaning.

What I changed
There are two commits. The first one, let trigger expressions start and end with blanks, is unchanged since the first review. The second commit has been replaced, not added to. The earlier second commit (9fe371a, with a token pass and position fixes for every expression) is gone. In its place is a much smaller one that follows @craigbarratt's simpler variant: wrap only a multi-line expression, and strip a one-line one as the first commit does. @dmamelin's review shaped what it keeps out: no token pass, position fixes only for multi-line expressions, tests that don't pin Python's exact error positions, and no new syntax.

From the first commit:

  • strip_trigger_expr() in trigger.py removes spaces, tabs and new lines around an expression.
  • With several @state_trigger entries, the callers strip each entry, and any_trigger_exprs() puts each one on its own lines inside the any([...]), so a trailing # comment can't swallow the , or ]) after it. The any([...]) is kept, so all entries are still evaluated, as before.
  • A bare state name is recognised after stripping, so " pyscript.a " means any change to pyscript.a, and the name is exact.

In the second commit:

  • New AstEval.parse_trigger_expr() in eval.py. It strips the expression first.

    • One line after stripping: it's parsed exactly as in the first commit, through AstEval.parse. Its error positions are Python's own. Nothing new is accepted or rejected: a, b is still a tuple (always true), and (x := 1) still works.
    • Still has a line break (\n or \r) after stripping: it's parsed as "(" + expr + "\n)", without stripping, as @craigbarratt suggested. So it reads as it would inside brackets in Python. It needs no brackets of its own, and any of its lines can end with a # comment. Its line numbers stay as written.
  • Errors point at the user's own text. The text shown in error messages is the expression as written, split into lines the way Python counts them (\r\n, \r and \n). Those lines are joined with \n before the brackets are added. Python reads \r\n and \r as \n anyway, even inside strings, so nothing else changes. But the added ) is always on a line of its own, even after a final lone \r (which would otherwise join the added \n into one line break).

    • After parsing, the positions on line 1 move one place left, for the added (. So an error while the expression runs, like a division by zero, points at the right place. Later lines are unchanged.
    • A syntax error is moved the same way and raised again as a new SyntaxError. Its lineno, offset, end_lineno, end_offset, text and args all agree, so the logged message and the error a script catches are the same.
    • An error that Python finds at the added ), when the expression stops short like x == 1 and, is reported at the end of the last line that isn't blank.
    • A bracket the user leaves open makes Python blame the added (. That's reported at the start of the first line. It isn't traced back to the user's own bracket, since that would need the token pass again.
    • EvalExceptionFormatter gets a small change: it treats parse_trigger_expr like parse.
  • No new syntax, as @dmamelin asked. Over several lines, the added brackets would make a few things valid that aren't valid without them. A short check after parsing gives each one a SyntaxError that says what's wrong:

    Written over several lines, without brackets of its own Error
    a bare generator expression, like x == 1 for x in y (forgetting any(), so it would always be true) generator expression must be inside brackets
    a bare tuple whose line break needs the brackets, like a, then b, also with * tuple must be inside brackets
    only comments expression is empty
    text that closes the added bracket early, like a and then b) or (c unmatched ')'
    a bare := ':=' must be inside brackets
    a bare yield or yield from 'yield' must be inside brackets

    How it tells them apart:

    • Python reports where each part of an expression starts. For the first four, it says the whole expression starts at our added (. A user's own expression always starts after it. For a tuple or generator in the user's own brackets, the start is the user's (.
    • A bare := or yield can't be told apart that way, because Python drops plain brackets from its result. For these only, the text is parsed once more as a keyword value, f(value=...). There a bare one is an error and a bracketed one isn't.
    • The error points at the first part of the expression the user wrote.
    • Inside the user's own brackets, all of these still work as they do in Python: (x == 1 for x in y), any(x == 1 for x in y), (a, b), (), (x := 1), (yield 1), (yield from a).
    • Nothing the first commit accepted is rejected. Before giving one of these errors, the check parses the stripped text the way the first commit does. If that works, the expression is parsed exactly as before, with the same tree and the same positions, counted from the stripped text as before. These look like the tuples above but don't need the added brackets: a, b followed by a comment line, a, ( with the bracket closed on a later line, a, \ continued on the next line, and a tuple holding a triple-quoted string that runs over several lines.
  • parse_trigger_expr() is used everywhere a trigger expression is parsed:

    • the current decorators, through create_expression in decorators/base.py: @state_trigger, @state_active, the expressions of @event_trigger, @mqtt_trigger, @webhook_trigger and @webhook_handler, and task.wait_until;
    • the legacy decorators (TrigInfo in trigger.py): @state_trigger, @state_active and the event, MQTT and webhook expressions;
    • the legacy task.wait_until (TrigTime.wait_until): the state, event, MQTT and webhook expressions. The legacy code has no @webhook_handler.
  • The @state_trigger callers (in decorators/state.py, TrigTime.wait_until and TrigInfo) now use a stripped copy only to recognise a bare state name. They pass the entry on as written, so a single multi-line expression keeps its line numbers. With several expression entries, each entry is still stripped before it goes into the any([...]); that now happens inside any_trigger_exprs(). Only expression entries are counted, after the bare names are taken out, so one bare name plus one expression is parsed as that expression alone.

  • Not changed: @time_trigger and @time_active (they have their own format), eval(), ordinary script code and AstEval.parse. They keep Python's exact rules.

The second commit adds 108 lines and removes 24 in eval.py, trigger.py and decorators/. The commit it replaces added 170 and removed 59.

Testing

  • New unit tests at the end of tests/test_unit_trigger.py. They check behaviour by comparing with what Python itself does with the same text, so no Python error message or position is written into them. Only positions this code chooses (a rejection, an error at the added )) are worked out in the test:
    • test_parse_trigger_expr_one_line (16 expressions): a one-line expression with blanks, a trailing comment, a, b, (x := 1), a bare x := 1, a bare generator, a) or (b, a cut-short line, a final \, only a comment, only blanks, and non-English letters. Each gives the same tree, with the same positions, or the same error (message, line, offset and text), as Python gives for the stripped text. That is what the first commit does.
    • test_parse_trigger_expr_several_lines (25 expressions): multi-line expressions without brackets, including Is it possible to use multiline strings in state trigger decorators? #617's shape, comments on any line, a comment line first, blank lines, a \ continuation, \r\n and a lone \r, non-English letters on the first line, an f-string holding ), a lambda and a bracketed walrus. Plus the user-bracketed forms above, each after a comment line and indented before a comment line. Each gives the same tree as Python does for the text inside brackets. Every part of the tree points at the same text in the expression as written.
    • test_parse_trigger_expr_needs_brackets (14 cases): the 7 rejected forms from the table above other than comments only (generator, tuple, tuple with *, early close, :=, yield, yield from), each written over several lines, once after a comment line and once indented. Each gives a SyntaxError on the right line, at the first character the user wrote, with that line's text, and args agrees.
    • test_parse_trigger_expr_empty (2 cases): comments only, over several lines.
    • test_parse_trigger_expr_syntax_error (8 cases): syntax errors on the first line (also with non-English letters) and on later lines, a cut-short expression with blank lines after it, cut-short expressions with \r and \r\n line endings that end in a line break, and an unclosed bracket. Each is at Python's place for the text inside brackets, moved one place left on line 1, or at the end of the last line that isn't blank when Python stops at the added ).
    • test_parse_trigger_expr_still_valid (7 expressions): multi-line text the first commit accepts that looks like a tuple needing brackets, such as a, b then a comment line, a, ( closed on a later line, a \ continuation, a tuple holding a multi-line triple-quoted string, and (a ), b. Each gives the same tree, with the same positions, as the first commit.
    • test_parse_trigger_expr_fuzz: 20,000 random texts built from pieces such as names, commas, brackets, and, for, :=, yield, comments, \, line breaks of each kind and a triple-quoted string, with a fixed seed. Of these, 1,021 parse as the first commit parses them, 343 of them over several lines. Each of those still parses, to the same tree.
  • test_trigger_expression_whitespace in tests/test_decorator_errors.py, from the first commit, extended. It runs with the current and the legacy decorators. Each trigger really fires when its condition becomes true, and not before:
    • Is it possible to use multiline strings in state trigger decorators? #617's example exactly as written (f-string, lines ending in and , state_hold_false=0), as a single @state_trigger and as one of two expressions;
    • a multi-line expression without brackets, with a comment on each line, and ones with \r\n and a lone \r;
    • bare names with blanks, alone and mixed with multi-line expressions that have comments;
    • a one-line a, b (fires on any change) and (k := ...) == '1', as before;
    • multi-line @state_active, @event_trigger and @mqtt_trigger expressions (MQTT subscriptions are patched in the test);
    • task.wait_until with multi-line state_trigger, event_trigger and mqtt_trigger expressions;
    • a script catching the SyntaxError from task.wait_until for a one-line and a multi-line expression. It reads the line, the place and the text of the expression as written.
  • test_trigger_expression_error_messages, which replaces the first commit's test_trigger_expression_whitespace_syntax_error, runs in both decorator modes. For 8 functions it checks the logged line number, the code line shown and the marker under it, not Python's wording. Where Python chooses the place, the expected frame is built from Python's own error, or its tree, for the same text (moved one place left on line 1) and drawn by Python's traceback module. Literal positions are only used where this code chooses the place: cut short, the unclosed bracket and the bare generator:
    • syntax errors: one on the first line, one on a later line, a one-line expression with blanks, a cut-short expression, an unclosed bracket and a bare generator;
    • errors while running: one on the first line and one on a later line.
  • test_webhook_trigger_expression_over_several_lines (both modes, including task.wait_until(webhook_trigger=...)) and test_webhook_handler_expression_over_several_lines, in tests/decorators/test_webhook.py.
  • From the first commit, test_trigger_expression_comments, test_script_indentation_stays_strict and the three strip_trigger_expr() unit tests are kept unchanged and still pass. The fake AstEval in tests/test_decorator_manager.py now records parse_trigger_expr().
  • Is it possible to use multiline strings in state trigger decorators? #617's example as a single @state_trigger fails on the first commit with SyntaxError: invalid syntax, in both decorator modes, and passes with this change.
  • On Python 3.14: the full test suite (324 tests), ruff, pylint, mypy, codespell and sphinx-build -W pass. The branch merges cleanly into current master, and the suite passes on the merged result (328 tests).

Docs
In the @state_trigger section of docs/reference.rst, the note from the first commit is replaced. It now says:

  • a trigger expression may start or end with spaces, tabs or new lines, which are ignored;
  • an expression written over several lines, for example in a triple-quoted string, is read as if it were inside brackets, so it needs no brackets of its own, and any of its lines can end with a # comment. There's a short example;
  • an expression over several lines can't rely on those brackets for anything else. A bare generator expression (forgetting the any()), a bare tuple that needs them for its line break, an empty expression, or a bare := or yield gives a SyntaxError. Inside brackets of your own they work as they do in Python;
  • the same goes for @state_active, task.wait_until and the expressions of @event_trigger, @mqtt_trigger, @webhook_trigger and @webhook_handler.

The sentence saying that a multi-line expression needs brackets is gone.

Note

  • For a multi-line expression, some syntax errors now give Python's message for the text inside brackets. For example, a b and followed by a line c now says invalid syntax. Perhaps you forgot a comma?. One-line expressions keep Python's exact messages and positions.
  • An unclosed bracket in a multi-line expression is reported at the start of the first line, which is often blank in a triple-quoted string. Then the log shows the line number and the message '(' was never closed, but no code line.
  • Python's traceback display leaves out the ^ marker when it would cover the whole code line. The caught SyntaxError still has the positions.
  • With several @state_trigger entries, error messages show the joined any([...]) text, and line numbers count from it, as before. A bare tuple entry like "a, b" still becomes two items of the any([...]) there, as it always has. The earlier second commit had changed that; this one doesn't.

)

A trigger expression with a leading space or new line, such as
@state_trigger(""" pyscript.a == 'x'"""), failed with IndentationError and
the trigger was never created.

Surrounding spaces, tabs and new lines are now stripped from a trigger
expression before it is parsed, for @state_trigger, @state_active and the
filters of @event_trigger, @mqtt_trigger and @webhook_trigger, for both the
current and the legacy decorators, and for task.wait_until. Bare state names
are stripped before they are recognised, so " pyscript.a" still means any
change. Syntax errors show the stripped expression. The time triggers, eval()
and script code are unchanged.

Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
@craigbarratt

Copy link
Copy Markdown
Member

Thanks @HoneyBearTech. The stripping works, but the example in #617 still fails: its lines end in and with no brackets around the whole expression, which is a SyntaxError after stripping. It's also inconsistent: with two or more @state_trigger entries, each one is already inside the any([...]) brackets, so a multi-line entry works there but not on its own.

Could you parse each trigger expression as "(" + expr + "\n)" instead? That handles the leading and trailing blanks too, lets any multi-line expression work as it would inside brackets in Python, and keeps a trailing # comment working. The error report would need to adjust the first line's offset by one. The docs could then drop the note that a multi-line expression needs brackets.

@craigbarratt

Copy link
Copy Markdown
Member

A simpler variant: only wrap when the expression contains a new line, and otherwise just strip it, as you do now. Single-line expressions then keep their exact error offsets. For a multi-line one, "(" + expr + "\n)" without stripping keeps the line numbers the same as the original, and only shifts the columns on the first line by one. That first line is usually empty in a triple-quoted string.

@HoneyBearTech HoneyBearTech changed the title Let trigger expressions start and end with blanks (#617) Let trigger expressions start and end with blanks and span lines (#617) Nov 22, 2026
@HoneyBearTech

Copy link
Copy Markdown
Contributor Author

Thanks @craigbarratt, you're right on all counts. I've added a second commit on top of the first, so you can see what changed since your review. I'm happy to squash them.

The #617 example. It now works. test_trigger_expression_whitespace runs #617's example exactly as written: the f-string, the lines ending in and , and state_hold_false=0. It runs as a single @state_trigger and as one of several, with the current and the legacy decorators. The trigger fires only once the whole condition is true. The same expression is also in test_parse_trigger_expr_matches_cpython. On the first commit, the single-trigger case still fails with SyntaxError: invalid syntax.

One entry vs several. Each @state_trigger entry now gets its own brackets inside the any([...]), as any([(e1\n), (e2\n)]), so an entry behaves the same alone or as one of several. I kept any([...]), so all entries are still evaluated, as before.

Parsing as "(" + expr + "\n)". Done, in a new AstEval.parse_trigger_expr() in eval.py. Everything that parses a trigger expression uses it:

  • the current decorators, through create_expression in decorators/base.py: @state_trigger, @state_active, @event_trigger, @mqtt_trigger, @webhook_trigger, @webhook_handler and task.wait_until;
  • the legacy paths in trigger.py (TrigInfo and TrigTime.wait_until).

That covers the leading and trailing blanks, so strip_trigger_expr() is gone. A bare state name with blanks around it, like " pyscript.a ", is stripped only for the "any change" check. AstEval.parse, eval() and script code are unchanged.

Trailing # comment. The new line before ) keeps it working, on the last line and on any middle line. That's why the first commit's any_trigger_exprs() is no longer needed, and it's gone too. test_trigger_expression_comments still passes, and test_trigger_expression_whitespace adds comments on middle lines.

The first line's offset in the error report. The error text is the expression exactly as written. After parsing, AST positions on line 1 move back by one, so errors while the expression runs point at the right place. A SyntaxError is moved the same way before it's raised again. That includes the lineno, offset, end_offset, text and args a script can catch, not just the logged message. Later lines are unchanged. When the expression is cut short, like x == 1 and, the error falls on the added ), and I report it at the last character of the last line that isn't blank. In EvalExceptionFormatter, the only change is that it treats parse_trigger_expr like parse. Tests:

  • test_parse_trigger_expr_errors (16 cases), test_parse_trigger_expr_errors_match_cpython and test_parse_trigger_expr_several_errors check every field;
  • test_trigger_expression_error_messages checks the logged line and marker for 11 syntax errors and 3 run-time errors, in both decorator modes.

The docs note. In the @state_trigger section of docs/reference.rst, the note now says that a trigger expression is read as if it were inside brackets: it can start and end with blanks, run over several lines without brackets of its own, and end a line with a # comment. There's a short example. The "needs brackets" sentence is gone. The list of decorators it applies to now includes @webhook_handler.

Beyond what you asked, so you can say if you'd rather drop them:

  • An expression that is empty, only blanks or only a # comment gives SyntaxError: expression is empty. Inside brackets it would otherwise be (), which is never true, so the trigger would quietly never fire. A written () still works.
  • Text that closes the added bracket early, like a) or (b, gives unmatched ')', as Python says for that text. Inside brackets it would otherwise parse as one expression. An unclosed bracket of the user's own is reported at that bracket, not at the added one.

Both are one short pass over the expression's tokens with the tokenize module, so brackets inside strings and comments are skipped. I'm happy to take this out if you'd rather keep it minimal.

One small change in behaviour: an entry written as a bare tuple, like "a, b", used to become two items of the any([...]) when there were several entries. Now it's one tuple, which is always true, as it already was for a single trigger. I've noted it in the description.

@dmamelin

Copy link
Copy Markdown
Contributor

+1 to @craigbarratt's simpler variant: wrap only multi-line expressions, strip single-line ones.

The current version solves a small problem with a lot of machinery: a tokenize pass, position remapping for every expression, and tests that pin exact CPython error offsets. It also quietly makes new syntax valid, like a bare generator, walrus, or a, b as one tuple. Once that ships it becomes API we have to keep. A bare generator is a real footgun: forget any() and the trigger fires on every change.

…m-components#617)

Stripping the blanks wasn't enough for custom-components#617's own example: its lines end
in "and" with no brackets around the whole expression. As one of several
@state_trigger entries it already worked, inside the any([...]).

A trigger expression that still has a line break after stripping is now
parsed unstripped as "(" + expr + "\n)", by AstEval.parse_trigger_expr().
Its line numbers stay as written, and positions on its first line move
back by one, in the logged error and in a caught SyntaxError. A one-line
expression is stripped and parsed exactly as before.

Nothing becomes valid only because of the added brackets: over several
lines, a bare generator expression, a bare tuple, an empty expression,
"a) or (b", and a bare := or yield give a SyntaxError. Inside the user's
own brackets they work as before, and anything that parsed before still
parses as before, such as a tuple followed by a comment line.

Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
@honeybeartech-homelab-automation
honeybeartech-homelab-automation Bot force-pushed the fix-trigger-expr-whitespace-617 branch from 9fe371a to a2e13b7 Compare November 22, 2026 22:47
@HoneyBearTech

Copy link
Copy Markdown
Contributor Author

Thanks @craigbarratt and @dmamelin. Sorry, I missed the 20:21 comment before my earlier reply, which answered only the first suggestion.

I've replaced the second commit. I didn't add a third on top. The first commit, let trigger expressions start and end with blanks, is unchanged. The new second commit, let multi-line trigger expressions span lines without brackets, follows the simpler variant. In eval.py, trigger.py and decorators/ it adds 108 lines and removes 24. The commit it replaces added 170 and removed 59. The description is updated.

@craigbarratt:

Only wrap when the expression contains a new line. Done, in AstEval.parse_trigger_expr() in eval.py. It strips the expression first. Only if a line break (\n or \r) is left after that is it parsed as "(" + expr + "\n)". Everything that parses a trigger expression uses it:

  • the current decorators, through create_expression in decorators/base.py;
  • the legacy TrigInfo and TrigTime.wait_until in trigger.py.

Otherwise just strip it, keeping the exact error offsets. A one-line expression is stripped and goes through AstEval.parse exactly as in the first commit, so its errors are Python's own. test_parse_trigger_expr_one_line checks that for 16 expressions. Each gives the same tree, or the same error message, line, offset and text, as Python gives for the stripped text. So a, b and (x := 1) work as before, and a bare x := 1 is still an error.

Line numbers stay the same as the original. A multi-line expression is wrapped without being stripped, so its lines keep their numbers. That needed one more change: the @state_trigger callers used to strip each entry before parsing. Now, in decorators/state.py, TrigTime.wait_until and TrigInfo, the stripped copy is used only to recognise a bare state name. The entry itself is passed on as written. With several entries, each entry is still stripped before it goes into the any([...]); that now happens inside any_trigger_exprs(). test_trigger_expression_error_messages checks the reported line for errors on line 1 and on later lines, in both decorator modes.

Only the columns on the first line shift by one. After parsing, positions on line 1 move one place left, which is a five-line loop. So an error while the expression runs points at the right place. A syntax error is moved by _trigger_syntax_error(), in all the fields a script can read. Two cases need more than the shift:

  • When the expression stops short, like x == 1 and, Python finds the error at the added ). It's reported at the end of the last line that isn't blank.
  • A bracket the user leaves open makes Python blame the added (. That's reported at the start of the first line, not at the user's bracket. Finding the user's bracket would need tokens again.

The lines are split the way Python counts them (\r\n, \r, \n) and joined with \n before the brackets are added, so a final lone \r can't hide the added ).

test_parse_trigger_expr_syntax_error and test_parse_trigger_expr_several_lines check the positions against Python's for the text in brackets. test_trigger_expression_error_messages checks the code line and the marker in the log.

@dmamelin:

The tokenize pass. Gone, along with check_added_brackets() and its tests.

Position remapping for every expression. It now runs only for a multi-line expression. It's the five-line loop above and _trigger_syntax_error(), which has about a dozen lines of logic. One-line expressions aren't touched.

Tests that pin exact CPython error offsets. Gone. Wherever Python chooses the place, the tests ask Python. The new unit tests at the end of tests/test_unit_trigger.py parse the same text with Python and compare. The log test, test_trigger_expression_error_messages, builds each expected frame from Python's own error, or its tree, for the same text, moved one place left on line 1, and draws it with Python's traceback module. It checks only that the error is a SyntaxError or ZeroDivisionError, not the wording. Literal positions are left only where this code chooses the place: an expression that stops short, an unclosed bracket, and the new rejection errors.

No new syntax. The only new thing is that a line break no longer needs brackets. Over several lines, the added brackets would make a few forms valid. A short check after parsing gives each one a SyntaxError, pointing at the first character the user wrote:

  • a bare generator expression gives generator expression must be inside brackets;
  • a bare tuple that needs the brackets for its line break, like a, then b, also with *, gives tuple must be inside brackets;
  • an expression that's only comments gives expression is empty;
  • text that closes the added bracket early, like a and then b) or (c, gives unmatched ')';
  • a bare := gives ':=' must be inside brackets;
  • a bare yield or yield from gives 'yield' must be inside brackets.

Python reports where each part of an expression starts. For the first four, it says the whole expression starts at our added (, and a user's own expression always starts after it. A bare := or yield can't be told apart that way, because Python drops plain brackets from its result. So for those three, the text is parsed once more as a keyword value, f(value=...), where a bare one is an error and a bracketed one isn't.

Nothing that parsed before is rejected. Before giving one of these errors, the check parses the stripped text the way the first commit does. If that works, the expression is parsed exactly as before. So a, b followed by a comment line, a, ( with the bracket closed on a later line, a \ continuation, and a tuple holding a triple-quoted string over several lines all still work. test_parse_trigger_expr_still_valid covers those. test_parse_trigger_expr_fuzz tries 20,000 random texts with a fixed seed: the 1,021 that parse on the first commit (343 of them over several lines) all still parse, to the same tree.

The same forms in the user's own brackets still work: (x == 1 for x in y), any(x == 1 for x in y), (a, b), (), (x := 1), (yield 1) and (yield from a). test_parse_trigger_expr_needs_brackets (14 cases) and test_parse_trigger_expr_several_lines cover each form both ways, after a comment line and indented. On one line, a, b is still a tuple, as it was before this PR. With several entries, a tuple entry is still split into items of the any([...]), as before. The earlier second commit had changed that.

The bare generator footgun. Over several lines it's now an error with that message, not a trigger that always fires. On one line it was already a SyntaxError from Python, and it still is. The docs say so too. In the @state_trigger section of docs/reference.rst, the note now says:

  • an expression may start and end with blanks;
  • an expression over several lines is read as if inside brackets, so it needs no brackets of its own, and any of its lines can end with a # comment;
  • it can't rely on those brackets for anything else. A bare generator expression (forgetting the any()), a bare tuple that needs them for its line break, an empty expression, or a bare := or yield gives a SyntaxError.

#617's example now works as a single @state_trigger, in both decorator modes (test_trigger_expression_whitespace). On the first commit alone it fails with SyntaxError: invalid syntax. The full suite, ruff, pylint, mypy, codespell and sphinx-build -W pass on Python 3.14. The branch merges cleanly into master.

@craigbarratt craigbarratt left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @HoneyBearTech, this is what I had in mind, and rejecting the forms that only work because of the added brackets addresses @dmamelin's concern. Approving. One nit: a line in the new docs paragraph in docs/reference.rst is much longer than the rest; I'll fix that.

@craigbarratt
craigbarratt merged commit 8b3fde3 into custom-components:master Nov 22, 2026
6 checks passed
@dmamelin

Copy link
Copy Markdown
Contributor

Looking at this again after it was merged, I think it ended up over-engineered: the gain is small and the cost is noticeable. I'd like to discuss it before the release.

The gain

#617 is a "can I do this" question, not a bug, and a comment there already gave a working approach: adjacent f-strings inside brackets. The example from the issue works without this PR once two characters are added, ( after """ and ) before the closing """:

@state_trigger(f"""(
    {_state_sensor} in ['recently occupied', 'unoccupied', 'dormant', 'unavailable'] and
    (sensor.octoprint_actual_tool0_temp == 'unavailable' or float(sensor.octoprint_actual_tool0_temp) <= 110) and
    (sensor.octoprint_actual_bed_temp == 'unavailable' or float(sensor.octoprint_actual_bed_temp) <= 110)
)""", state_hold_false=0)

Explicit brackets are plain Python that users already know. I'd keep stripping the blanks around the expression: it fixes the IndentationError and adds no complexity.

Hidden problems

Inside the implicit brackets a line break no longer ends the expression, so a missing operator gets joined with the next line. In plain Python this is a SyntaxError when the script loads; here the expression parses without error:

# Next line starts with "(": the value before it gets called
@state_trigger("""
    binary_sensor.door == 'on'
    (input_boolean.away == 'on' or input_boolean.night == 'on')
""")
# parsed as: binary_sensor.door == 'on'(...)
# TypeError: 'str' object is not callable -- only when the trigger fires

# Next line starts with a string: the strings are joined and the comparisons chain
@state_trigger("""
    input_select.mode == 'away'
    'on' == input_boolean.alarm
""")
# parsed as: input_select.mode == 'awayon' == input_boolean.alarm
# always False, no error at all

# Next line starts with "-": it becomes a binary operator
@state_trigger("""
    sensor.temp > 20
    -5 < sensor.temp_delta
""")
# parsed as: sensor.temp > 20 - 5 < sensor.temp_delta
# wrong logic, no error at all

The error for an unclosed bracket also got worse. The added ) closes the user's bracket, and Python then reports the added (:

@state_trigger("""
    pyscript.a == 'on' and (pyscript.b == 'on' or
    pyscript.c == 'on'
""")
# now:              '(' was never closed -- on line 1, with empty text
# without wrapping: '(' was never closed -- at the bracket before pyscript.b

Difference from CPython, and the cost

In Python, a multi-line expression without brackets is an error, and inside brackets anything goes. Now it's neither: without brackets it's allowed, with exceptions — a bare generator, a tuple, :=, yield, an empty expression, an early ). To reject those, parse_trigger_expr checks for nodes starting at (1, 0), parses the text a second time through f(value=...) (only to find out whether :=/yield had brackets of their own), and remaps error positions. Much of this depends on how CPython assigns AST positions. Positions in the tree are also counted differently, from the original or from the stripped text, depending on which path the parse took. The result is a separate dialect that has to be documented, tested and maintained.

To be fair, several @state_trigger entries were already joined inside any([...]), so this behavior existed there before, and this PR extended it to a single entry. So the question is also which way to make them consistent.

@craigbarratt, what do you think? Is the implicit wrapping worth it, or is stripping plus a line in the docs ("put a multi-line expression in brackets") enough? It would be good to decide before the release; removing it afterwards would be a breaking change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Is it possible to use multiline strings in state trigger decorators?

3 participants